#include <iostream>
#include "http.hpp"

#define WWWROOT "./wwwroot"

std::string RequestStr(const HttpRequest& req){
    std::stringstream ss;
    ss << req._method << " " << req._path << " "<< req._version << "\r\n";
    for(auto&param:req._params){
        ss << param.first << ":" << param.second << "\r\n";
    }
    for(auto &head:req._headers){
        ss << head.first << ":" << head.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}
void Hello(const HttpRequest&req,HttpResponse*rsp){
    std::string *file = nullptr;
    Util::ReadFile("./wwwroot/index.html", file);
    assert(file != nullptr);
    rsp->SetContent(file->c_str(), "html/text");
    //->SetContent(RequestStr(req), "text/plain");
}
void Login(const HttpRequest&req,HttpResponse*rsp){
    rsp->SetContent(RequestStr(req), "text/plain");
}
void PutFile(const HttpRequest&req,HttpResponse*rsp){
    std::string pathname = WWWROOT + req._path;
    DBG_LOG("ls:%s", req._body.c_str());
    Util::WriteFile(pathname, req._body);
}
void DelFile(const HttpRequest&req,HttpResponse*rsp){
    std::string FileName = WWWROOT + req._path;
    const char *filename = FileName.c_str();
    int res = remove(filename);
    if(res==0){
        INF_LOG("删除文件%s成功", filename);
    }
    else{
        DBG_LOG("删除文件%s失败", filename);
        perror("删除文件失败！");
    }
}
int main()
{
    HttpServer server(8080);/*第二个参数可以给超时时长*/
    server.SetBasedir(WWWROOT);
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);
    server.SetThreadCount(5);
    server.Listen();
}